<template>
    <div ref="msgContainer" class="output-logs">
        <p v-for="log in logs" :key="log.msgLine" :class="'msg '+log.type" >
            {{ log.msgLine }}
        </p>
    </div>
</template>
<script lang="ts" setup>
import { ref,onMounted, onUnmounted } from 'vue';
import type { LogEventMsg } from '@/scripts/types'
import { EventsOn,EventsOff,WindowSetAlwaysOnTop } from '../../../wailsjs/runtime/runtime';

interface LogMsg {
    type: string;
    msgLine: string;
}

const logs = ref<LogMsg[]>([]);
const msgContainer = ref<HTMLDivElement>();

const appendLog = (log: LogEventMsg) => {
    if (logs.value[logs.value.length - 1]?.type == log.Msgtype && logs.value[logs.value.length - 1]?.msgLine.lastIndexOf("\n") < 0) {
        logs.value[logs.value.length - 1].msgLine += log.Msg;
    } else {
        logs.value.push({
            type: log.Msgtype,
            msgLine: log.Msg
        });
    }
    setTimeout(()=>{
        msgContainer.value?.scrollTo(0, msgContainer.value.scrollHeight);
    }, 100)
    
}

onMounted(() => {
   logs.value = [];
   EventsOn("cmdoutput", appendLog);
   WindowSetAlwaysOnTop(true);
});
onUnmounted(() => {
   EventsOff("cmdoutput");
   WindowSetAlwaysOnTop(false);
})
</script>
<style lang="scss" scoped>
.output-logs {
    height: calc(100vh - 180px);
    width: 100%;
    overflow-y: auto;
    overflow-wrap: normal;
    background-color: var(--vt-c-white-soft);
    border: 1px solid var(--fv-c-setting-light-back);
    .msg {
        padding: 5px;
        font-size: 12px;
        &.error {
            color: var(--fv-c-text-red);
        }
        &.info {
            color: var(--fv-c-text-black);
        }
        &.warn {
            color: var(--fv-c-text-yellow);
        }
        &.success {
            color: var(--fv-primary-color);
        }
    }
}
</style>